//
//  LJOAuthViewController.swift
//  LJWeibo
//
//  Created by 连俊杨 on 2017/10/19.
//  Copyright © 2017年 yang_ljun. All rights reserved.
//

import UIKit
import SVProgressHUD

class LJOAuthViewController: UIViewController {
    
    fileprivate var webView: UIWebView = UIWebView()
    
    override func loadView() {
        view = webView
        view.backgroundColor = UIColor.white
        webView.scrollView.isScrollEnabled = false
        title = "用户登录"
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", target: self, action: #selector(close), isBack: true)
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(autoFill))
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        loadWebView()
        
        /// 添加网页代理
        webView.delegate = self
    }
    
    fileprivate func loadWebView() {
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WBAppKey)&redirect_uri=\(WBRedirectRUI)"
        
        guard let url = URL(string: urlString) else {
            return
        }
        
        // 建立请求
        let urlRequest = URLRequest(url: url)
        
        // 执行请求
        webView.loadRequest(urlRequest)
    }
    
    
    /// MARK: 事件
    @objc fileprivate func close() {
        SVProgressHUD.dismiss()
        dismiss(animated: true, completion: nil)
    }
    
    @objc fileprivate func autoFill() {
        let js = "document.getElementById('userId').value = \"18621553639\";" + "document.getElementById('passwd').value = \"a18621553639\""
        webView.stringByEvaluatingJavaScript(from: js)
    }
}

// MARK: - webView的代理处理
extension LJOAuthViewController: UIWebViewDelegate {
    /// webView将要开始加载请求
    ///
    /// - Parameters:
    ///   - webView: webView
    ///   - request: 将要加载的请求
    ///   - navigationType: 导航类型
    /// - Returns: 是否加载
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        /// 如果不包含百度的回调，说明正在处理登录
        if request.url?.absoluteString.hasPrefix(WBRedirectRUI) == false {
            return true
        }
        
        /// 代码到此，都包含百度
        if request.url?.query?.hasPrefix("code=") == false {
            /// 取消登录
            close()
            return false
        }
        
        /// 代码到此，登录成功,获取授权码
        let code = request.url?.query?.substring(from: "code=".endIndex) ?? ""
        /// 网络获取token
        LJNetworkManager.sharedManager.loadAccessToken(code: code) { (isSuccess) in
            if !isSuccess {
                SVProgressHUD.showInfo(withStatus: "登录失败")
            }
            else {
                /// 返回进入之前的页面，并刷新数据
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: UserLoginSuccessNotification), object: nil)
            }
            
            self.close()
        }
        
        return false
    }
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
}










